import {
  ForwardedRef,
  forwardRef,
  useEffect,
  useImperativeHandle,
  useMemo,
  useRef,
  useState,
} from "react";
import { ComponentBaseProps } from "../../common-component/CommonTypes";
import { Tooltip } from "tdesign-react";
import { IotDeviceData } from "_common/DataType";
import image from "./iot-jzj.png";
import "./IotGreaseComponent.less";
import { ViewerState } from "components";
import { getDeviceDataCache } from "utils/StorageUtil";
import { IotDevice } from "_common/entity";

export interface IotGreaseComponentStyle {
  color?: string;
  fontSize?: number;
  fontWeight?: number;
  fontFamily?: string;
  alignItems?: string;
  justifyContent?: string;
  borderColor?: string;
  borderRadius?: number;
  backgroundColor?: string;
}

export interface DeviceProps {
  terminalId: string;
  deviceCode: string;
  position: string;
}

export interface IotGreaseComponentProps extends ComponentBaseProps {
  style?: IotGreaseComponentStyle;
  device?: DeviceProps;
  standardStore?: any;
}

export interface IotGreaseComponentRef {
  updateConfig: (newConfig: IotGreaseComponentProps) => void;
  setEventHandler: (eventMap: Record<string, Function>) => void;
  updateIotData?: (data: IotDeviceData) => void;
}

export const IotGreaseComponent = forwardRef(
  (
    props: IotGreaseComponentProps,
    ref: ForwardedRef<IotGreaseComponentRef>
  ) => {
    const [config, setConfig] = useState<IotGreaseComponentProps>({
      ...props,
    });
    const { style, device } = config;
    const eventHandlerMap = useRef<Record<string, Function>>({});

    // 标准数据：烟感数据：value1: 0/1  value2: 电压  value1: 0:离线：1：正常：2 报警
    // 当前值
    const [data, setData] = useState<IotDeviceData>();
    const [deviceList, setDeviceList] = useState<IotDevice[]>([]);

    useEffect(() => {
      let cache = getDeviceDataCache();
      setDeviceList(cache);
    }, []);

    useImperativeHandle(ref, () => ({
      updateConfig: (newConfig) => setConfig({ ...newConfig }),
      setEventHandler: (eventMap) => (eventHandlerMap.current = eventMap),
      updateIotData: (data) => {
        if (data.deviceCode == device?.deviceCode) {
          setData(data);
        }
      },
    }));

    const tooltip = useMemo(() => {
      if (data?.status == 4)
        return <span className="text-gray-500">设备离线</span>;
      if (data?.status == 3)
        return <span className="text-gray-500">设备故障</span>;
      if (data?.status == 2)
        return <span className="text-red-500">设备报警</span>;
      if (data?.status == 1)
        return <span className="text-orange-500">设备预警</span>;
      if (data?.status == 0)
        return <span className="text-green-500">设备在线</span>;
    }, [data]);

    // 获取文字的颜色
    const getTextColor = () => {
      switch (data?.status) {
        case 0:
          return "#00a870";
        case 1:
          return "#ed7b2f";
        case 2:
          return "#C9353F";
        case 3:
          return "#a7a7a7";
        case 4: // 离线
          return "#a7a7a7";
        default:
          return "#a7a7a7";
      }
    };

    // 判断是否显示温度
    const hideTemp = useMemo(() => {
      if (data?.status == 4) return true;
      let _device = deviceList.find(
        (item) => item.deviceCode == device?.deviceCode
      );
      if (!_device) return false;
      return !_device?.deviceAttr?.showTemp;
    }, [data, deviceList]);

    return (
      <div
        className="iot-sj-component flex flex-row justify-around border border-1 border-cyan-500 cursor-pointer items-center h-full"
        style={{
          borderWidth: 1,
          borderStyle: "solid",
          borderColor: style?.borderColor,
          borderRadius: style?.borderRadius,
          backgroundColor: style?.backgroundColor,
          minHeight: 120,
        }}
      >
        <div className=" absolute" style={{ bottom: -35 }}>
          <span className="text-cyan-500 text-l">{device?.position}</span>
        </div>
        <Tooltip content={tooltip}>
          <div
            className="left-img flex flex-col items-center justify-center"
            style={{ width: 45, height: "100%" }}
          >
            <img
              src={image}
              style={{ width: "100%", height: "75%" }}
              onClick={() => {
                ViewerState.handleClick(device?.deviceCode);
              }}
            />
            <span className="text-cyan-500 text-l">
              {device?.deviceCode == "" ? "未绑定" : device?.deviceCode}
            </span>
          </div>
        </Tooltip>
        <div
          className="flex flex-col items-left w-2/3"
          style={{ color: style?.color }}
        >
          <span
            className="text-green-500 text-item"
            style={{ color: getTextColor() }}
          >
            温度：{hideTemp ? "--" : (data?.value1 ?? "--")}℃
          </span>
          <span
            className="text-green-500 text-item"
            style={{ color: getTextColor() }}
          >
            电压：{data?.status == 4 ? "--" : (data?.value5 ?? "--")}v
          </span>
          <span
            className="text-green-500 text-item"
            style={{ color: getTextColor() }}
          >
            电流：{data?.status == 4 ? "--" : (data?.value2 ?? "--")}mA
          </span>
          <span
            className="text-green-500 text-item"
            style={{ color: getTextColor() }}
          >
            剩余次数：{data?.status == 4 ? "--" : (data?.value3 ?? "--")}次
          </span>
          <span
            className="text-green-500 text-item"
            style={{ color: getTextColor() }}
          >
            是否油堵：
            {data?.status == 4
              ? "--"
              : data?.value4 == null
                ? "--"
                : data?.value4 == 1
                  ? "是"
                  : "否"}
          </span>
        </div>
      </div>
    );
  }
);

export default IotGreaseComponent;
